using System;
using System.IO;
using System.Net;
using System.Text;
using System.Text.Json;

namespace baiduNLP
{
  public class GetAccessToken
  {
    public string AccessToken { get; set; }
    private string ClientId { get; set; }
    private string ClientSecret { get; set; }

    public GetAccessToken(string clientId = "vola8AKUwGMflU5tOj75GZia",
      string clientSecret = "nkyWtPN2iHIUlQjud5RZ55a98x094brM")
    {
      ClientId = clientId;
      ClientSecret = clientSecret;
      SetAccessToken();
    }

    private string AccessTokenUrlFormat()
    {
      StringBuilder sb = new StringBuilder();
      sb.Append("https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&");
      sb.AppendFormat("client_id={0}&", ClientId);
      sb.AppendFormat("client_secret={0}", ClientSecret);
      return sb.ToString();
    }

    private void SetAccessToken()
    {
      string token = null;
      string Url = AccessTokenUrlFormat();
      HttpWebRequest req = (HttpWebRequest) HttpWebRequest.Create(Url); //创建request
      req.Method = "Get";
      req.ContentType = "application/json";
      using (WebResponse response = req.GetResponse())
      {
        Stream stream = response.GetResponseStream();
        try
        {
          //获取内容
          using (StreamReader reader = new StreamReader(stream))
          {
            token = reader.ReadToEnd();
          }
        }
        finally
        {
          stream.Close();
        }
      }

      AccessTokenModel t = JsonSerializer.Deserialize<AccessTokenModel>(token);
      AccessToken = t.access_token;
    }
  }
}